//
//  REManager.m
//  kuku
//
//  Created by 清风徐来 on 2024/1/23.
//

#import "REManager.h"

@implementation REManager

/// 继续检测
+ (BOOL)needStepByStepCheck {
    // 2. 设备的语言是否包含 "en"
    const char *language = re_getSystemLanguageC(NO);
    NSString *languageString = [NSString stringWithUTF8String:language];
    if (![languageString.lowercaseString containsString:@"zh"]) {
        return YES;
    }

    // 3. 时区不是中国（"Asia/Beijing"、"Asia/Shanghai"、"Asia/ChongQing"）
    const char *timezone = re_getCurrentTimeZoneC(NO);
    NSString *timezoneString = [NSString stringWithUTF8String:timezone];
    if (!([timezoneString.lowercaseString isEqualToString:@"asia/beijing"] || [timezoneString.lowercaseString isEqualToString:@"asia/shanghai"] || [timezoneString.lowercaseString isEqualToString:@"asia/chongqing"])) {
        return YES;
    }

    // 4. 当前时间是否早于设置的本地时间
    NSInteger localTime = [[REManager re_loadLocalTimeFromPlist:nil] integerValue];
    NSInteger currentTime = [REManager re_getCurrentTimestampInChinaTimeZone];
    if (currentTime < localTime) {
        return YES;
    }

    // 所有检查都通过
    return NO;
}

const char * re_getSystemLanguageC(BOOL passed) {
    if (passed) {
        return "zh";
    }
    NSString *systemLanguage = [REManager re_getSystemLanguage:YES];
    const char *cStr = [systemLanguage UTF8String];
    char *cStrCopy = strdup(cStr);
    return cStrCopy;
}

const char * re_getCurrentTimeZoneC(BOOL passed) {
    if (passed) {
        return "asia/beijing";
    }
    NSString *timeZone = [REManager re_getCurrentTimeZone];
    const char *cStr = [timeZone UTF8String];
    char *cStrCopy = strdup(cStr);
    return cStrCopy;
}

// 获取语言
+ (NSString *)re_getSystemLanguage:(BOOL)withDefault {
    if (withDefault) {
        NSArray *languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
        NSString *currentLanguage = [languages objectAtIndex:0];
        return currentLanguage;
    }
    return @"Chinese";
}

// 获取时区
+ (NSString *)re_getCurrentTimeZone {
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    NSString *timeZoneName = [localTimeZone name];
    return timeZoneName;
}

/// 获取当前的时间戳 精确到秒
+ (NSInteger)re_getCurrentTimestampInChinaTimeZone {
    NSDate *currentDate = [NSDate date];
    NSTimeZone *chinaTimeZone = [NSTimeZone timeZoneForSecondsFromGMT:8 * 3600];
    NSInteger chinaTimestamp = (NSInteger)([currentDate timeIntervalSince1970] + [chinaTimeZone secondsFromGMTForDate:currentDate]);
    return chinaTimestamp;
}

/// 从info.plist中加载启用时间数据
+ (NSString *)re_loadLocalTimeFromPlist:(NSString *)time {
    NSBundle *sdkBundle = [NSBundle bundleForClass:[REManager class]];
    NSDictionary *infoDict = [sdkBundle infoDictionary];

    if (!infoDict) {
        return nil;
    }
    
    if (time) {
        return time;
    }
    
    // 2024-04-29 11:17:22
    return @"1615713145";
}

@end
